package cn.xianshu.mq2._01_hello;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者
 * 1.创建连接
 * 2.创建通道
 * 3.监听队列
 * 4.接收消息
 * 5.处理消息
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        //* 1.创建连接
        Connection connection = factory.newConnection();
        //* 2.创建通道
        Channel channel = connection.createChannel();

        //* 4.接收消息

        com.rabbitmq.client.Consumer callback = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("拿到消息了:" + new String(body));
                System.out.println("交换机:" + envelope.getExchange());
                System.out.println("消息的标签(id):" + envelope.getDeliveryTag());
                System.out.println("队列:" + envelope.getRoutingKey());
                // System.out.println("额外的参数!" + properties);
            }
        };
        //* 5.处理消息



        //* 3.监听队列
        channel.basicConsume(Producer.NAME_PRODUCER_HELLO, // 队列名
                false, // 手动处理消息 防止消息丢失
                callback); // 消息处理回调

    }


}
